package com.minivision.sdktestdemo.ui;


import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.bean.MusicBean;
import com.minivision.sdktestdemo.controler.ui.activity.MusicMiniPlayControler;
import com.minivision.sdktestdemo.controler.ui.activity.MusicSearchControler;
import com.minivision.sdktestdemo.controler.ui.list.ListControler;
import com.minivision.sdktestdemo.controler.ui.list.MusicListControler;
import com.minivision.sdktestdemo.event.DataModificationEvent;
import com.minivision.sdktestdemo.event.PlayMusicEvent;
import com.minivision.sdktestdemo.ui.view.MusicCtrlPopContentView;
import com.minivision.sdktestdemo.ui.view.PopupView;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SearchResultFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SearchResultFragment extends Fragment implements MusicSearchControler.SearchResult,
        MusicItemRecyclerAdapter.OnItemListener, OnFragmentUpdatedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public SearchResultFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SearchResultFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SearchResultFragment newInstance(String param1, String param2) {
        SearchResultFragment fragment = new SearchResultFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Bind(R.id.list)
    RecyclerView mListView;

    private MusicListControler mMusicListControler;

    SearchResultAdapter mAdapter;

    private MusicMiniPlayControler.PlayListGetter mPlayListGetter;

    @Override
    public void onItemClick(View v, int position) {
        PlayMusicEvent event = getPlayEvent(position);
        if (mPlayListGetter.getPlayList() != null && isListEqual(mPlayListGetter.getPlayList(), mMusicListControler.getBeans())) {
            event.mStatus = PlayMusicEvent.PLAY;
            mAdapter.notifyDataSetChanged();
            //拷贝对应的数据
            EventBus.getDefault().post(event);
        } else {
            DataModificationEvent e = new DataModificationEvent(mMusicListControler.getBeans(), DataModificationEvent.ACTION_GROUP_PLAY);
            EventBus.getDefault().post(e);
        }
    }

    boolean isListEqual(List<MusicBean> src, List<MusicBean> tar) {
        Set<MusicBean> set = new HashSet<>(src);
        if (set.size() != tar.size())
            return false;
        boolean flag = true;
        for (MusicBean bean : tar) {
            if (!set.contains(bean)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    public PlayMusicEvent getPlayEvent(int position) {
        String uri = mMusicListControler.getPath(position);
        //获取映射后的position
        Uri albumUri = mList.get(position).getmPicUri() == null ? Uri.EMPTY : mList.get(position).getmPicUri();
        PlayMusicEvent event = new PlayMusicEvent(mList.get(position).getmPath(),
                mList.get(position).getmMusicName(), mList.get(position).getmSingerName(),
                PlayMusicEvent.PLAY, albumUri, mList.get(position).getmLen());
        return event;
    }

    private PopupView mPopView;

    @Override
    public void onMoreItemClick(int position) {
        if (mPlayListGetter.getPlayList() == null) {
            mPopView.show(mMusicListControler.getBeans(), mMusicListControler.getBeans().get(position));
        } else {
            if (!isListEqual(mPlayListGetter.getPlayList(), mMusicListControler.getBeans())) {
                mPopView.show(mMusicListControler.getBeans(), mMusicListControler.getBeans().get(position));
            } else {
                mPopView.show(null, mMusicListControler.getBeans().get(position));
            }
        }
    }

    @Override
    public void update(PlayMusicEvent event) {
        //空的
    }

    @Override
    public void update(DataModificationEvent event) {
        if (mMusicListControler != null && mMusicListControler.notifyDataChanged()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    @Override
    public void setPlayEvent(PlayMusicEvent event) {
        //空的
    }

    public static class SearchResultAdapter extends RecyclerView.Adapter<MusicItemRecyclerAdapter.MusicViewHolder> {
        private MusicListControler mMusicListControler;
        private List<Integer> mFilters;
        private MusicItemRecyclerAdapter.OnItemListener mListener;


        public SearchResultAdapter(MusicListControler mMusicListControler) {
            this.mMusicListControler = mMusicListControler;
            mFilters = new ArrayList<>();
        }

        public void setItemClickListener(MusicItemRecyclerAdapter.OnItemListener listener) {
            mListener = listener;
        }

        public void filter(String text) {
            mFilters.clear();
            for (int i = 0; i < mMusicListControler.size(); ++i) {
                if (!text.isEmpty() && (mMusicListControler.getContent(i).toUpperCase().contains(text.toUpperCase())
                        || mMusicListControler.getTitle(i).toUpperCase().contains(text.toUpperCase()))) {
                    mFilters.add(i);
                }
            }
        }

        @Override
        public MusicItemRecyclerAdapter.MusicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_music_list_item_with_pic, parent, false);
            return new MusicItemRecyclerAdapter.MusicViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MusicItemRecyclerAdapter.MusicViewHolder holder, final int position) {
            holder.showAlbum(false);
            holder.showAlbumCover(false);
            holder.showIcon(false);
            holder.mContent.setText(mMusicListControler.getContent(mFilters.get(position)));
            holder.mTitle.setText(mMusicListControler.getTitle(mFilters.get(position)));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onItemClick(v, mFilters.get(position));
                }
            });
            holder.mImageMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onMoreItemClick(mFilters.get(position));
                }
            });
        }

        @Override
        public int getItemCount() {
            return mFilters.size();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mPopView = new PopupView(getActivity(), new MusicCtrlPopContentView(getActivity()));
    }

    public void setBeanList(List<MusicBean> list) {
        mList = list;
    }

    private List<MusicBean> mList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_search_result, container, false);
        ButterKnife.bind(this, view);
        mMusicListControler = new MusicListControler(getActivity(), mList);
        mAdapter = new SearchResultAdapter(mMusicListControler);
        mAdapter.setItemClickListener(this);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mListView.hasFixedSize();
        mListView.setAdapter(mAdapter);
        return view;
    }

    @Override
    public void updateSearchResult(String text) {
        if (mAdapter != null) {
            mAdapter.filter(text);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mPlayListGetter = (MusicMiniPlayControler.PlayListGetter) context;
    }
}
